/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/parser/deserializer/DefaultFieldDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: DefaultFieldDeserializer.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.parser.deserializer;

import java.lang.reflect.Type;
import java.util.Map;

import com.elancom.framework.commons.json.parser.DefaultJSONParser;
import com.elancom.framework.commons.json.parser.DefaultJSONParser.ResolveTask;
import com.elancom.framework.commons.json.parser.JSONToken;
import com.elancom.framework.commons.json.parser.ParserConfig;
import com.elancom.framework.commons.json.util.FieldInfo;

public class DefaultFieldDeserializer extends FieldDeserializer {

	private ObjectDeserializer fieldValueDeserilizer;

	public DefaultFieldDeserializer(ParserConfig mapping, Class<?> clazz, FieldInfo fieldInfo) {
		super(clazz, fieldInfo);
	}

	@Override
	public void parseField(DefaultJSONParser parser, Object object, Type objectType, Map<String, Object> fieldValues) {
		if (fieldValueDeserilizer == null) {
			fieldValueDeserilizer = parser.getConfig().getDeserializer(fieldInfo);
		}

		final Object value = fieldValueDeserilizer.deserialze(parser, getFieldType(), fieldInfo.getName());
		if (parser.getResolveStatus() == DefaultJSONParser.NeedToResolve) {
			final ResolveTask task = parser.getLastResolveTask();
			task.setFieldDeserializer(this);
			task.setOwnerContext(parser.getContext());
			parser.setResolveStatus(DefaultJSONParser.NONE);
		} else {
			if (object == null) {
				fieldValues.put(fieldInfo.getName(), value);
			} else {
				setValue(object, value);
			}
		}
	}

	@Override
	public int getFastMatchToken() {
		if (fieldValueDeserilizer != null) {
			return fieldValueDeserilizer.getFastMatchToken();
		}

		return JSONToken.LITERAL_INT;
	}
}
